#!/usr/bin/env python3
# coding: utf-8
"""
last edited at 2019-8-18
by Stone at BlueNet

其实主程序是robot.py，运行其中的loop()函数即可启动整个项目。但是习惯上程序的入口是main，
所以使用该名字一目了然入口在哪里。

另外，顺带增加遇到意外自动重启的功能(也许增加了稳定性吧)。
    在Ubuntu下测试，Ctrl + C 引发KeyboardInterrupt令程序出错，被成功捕捉并重启程序。若要
    中止程序，可以 Ctrl + Z 冻结程序，然后用Linux命令 jobs 查看程序编号，例如编号为 1，则
    用命令 kill %1 可终止程序。
"""
import logging
import sys
import os

import robot


def main():

    try:
        robot.loop()

    # TODO(Stone): some cleaning might need to be done before restart, such as release serial port.
    # python doc 16.1.6 Process Management:
    #   Open file objects and descriptors are not flushed, so if there may be data buffered on
    #   these open files, you should flush them using sys.stdout.flush() or os.fsync() before
    #   calling an exec* function.
    except BaseException as e:
        logging.error('Fatal error happens. error:{}'.format(repr(e)))
        logging.info('Restart program...')

        # I don't know why the arg0 should be 'python3', since sys.executable is already the path of interpreter.
        # I think I cannot get the point of the python doc:
        #   The arguments to the child process should start with the name of the command being run, but this
        #   is not enforced.
        #
        # Something confusing happens when you run os.execl('/bin/echo', 'a', 'b', 'c'), to see how the arguments
        # are passed. Well, after all, it works fine now.
        os.execl(sys.executable, 'python3', *sys.argv)


main()

